<?php

namespace app\Home\controller;

//公共控制器
use app\common\controller\Homecontroller;

//引入验证码
use think\captcha\Captcha;

//引入Cookie
use think\Cookie;

use think\Db;

class Post extends Homecontroller
{
    public function __construct()
    {
        //手动把父类的方法获取过来
        parent::__construct();
        $this->PostModel = model('Post.Post');
        $this->CateModel = model('Post.Cate');
        $this->UserModel = model('User.User');
        $this->ConfigModel = model('Config');
        $this->RecordModel = model('User.Record');
        $this->CommentModel = model('Post.Comment');
        $this->CollectModel = model('User.Collect');
    }
    // 我的帖子
    public function index()
    {
        $setup = $this->request->param('setup', false);
        $userid = Cookie::get('LoginUser')['id'];
        $id = $this->request->param('postid', 0);
        $counts =  $this->PostModel->where("userid=$userid")->count();
        $count = $this->CommentModel->where(['postid' => $id])->count();

        $publish = $this->PostModel->where("userid=$userid")->order("createtime", 'desc')->paginate(5);
        $pagestr = $publish->render();
        foreach ($publish as $key => $item) {
            $publish[$key]['visit'] = empty($item['visit']) ? 0 : count(explode(',', $item['visit']));
        }
        $this->assign([
            'setup' => $setup,
            'publish' => $publish,
            'count' => $count,
            'counts' => $counts,
            'pagestr' => $pagestr
        ]);
        return $this->fetch();
    }
    // 我的评论
    public function comment()
    {
        $setup = $this->request->param('setup', false);
        $userid = Cookie::get('LoginUser')['id'];
        $commentlist = $this->CommentModel->with('user', 'post')->where(['userid' => $this->LoginUser['id']])->order('createtime', 'desc')->paginate(5);
        $pagestr = $commentlist->render();
        // var_dump($hh);
        // exit;
        $this->assign([
            'setup' => $setup,
            'commentlist' => $commentlist,
            'pagestr' => $pagestr,
            'userid' => $userid,
        ]);
        return $this->fetch();
    }

    // 我的收藏
    public function collect()
    {
        $setup = $this->request->param('setup', false);
        $userid = Cookie::get('LoginUser')['id'];
        $count = $this->CollectModel->where("userid=$userid")->count();
        // $collection = $this->CollectModel->alias('c')->join('post p','c.postid = p.id')->order('c.createtime','desc')->paginate(5);
        $collection = $this->CollectModel->alias('c')->join('post p', 'c.postid = p.id')->join('user u', 'u.id=p.userid')->where("c.userid=$userid")->order('c.createtime', 'desc')->paginate(5);
        $pagestr = $collection->render();
        $this->assign([
            'setup' => $setup,
            'collection' => $collection,
            'count' => $count,
            'pagestr' => $pagestr
        ]);
        return $this->fetch();
    }
    // 消费记录
    public function record()
    {
        $setup = $this->request->param('setup', false);
        $userid = Cookie::get('LoginUser')['id'];
        $conunt = $this->RecordModel->where('userid', $userid)->count();
        $content = $this->RecordModel->where('userid', $userid)->paginate(10);
        $pagestr = $content->render();
        $this->assign([
            'setup' => $setup,
            'count' => $conunt,
            'pagestr'=> $pagestr,
            'content' => $content
        ]);
        return $this->fetch();
    }
    // 发帖
    public function add()
    {
        if ($this->request->isPost()) {
            // 获取所有参数
            $params = $this->request->param();
            //获取验证码
            $code =  $this->request->param('vercode', '');

            $LoginUser = Cookie::get('LoginUser');

            // 查询用户的数据
            $userInfo = $this->UserModel->find($LoginUser['id']);

            //判断验证码是否正确 如果结果返回true就是正确否则失败
            if (!captcha_check($code)) {
                $this->error('验证码输入错误');
                exit;
            }

            //根据附加功能类型去配置表里面查询相对的积分
            $StatePoint = $this->ConfigModel->where(['key' => "PostState{$params['state']}"])->value('value');

            $StatePoint = is_numeric($StatePoint) ? abs($StatePoint) : 0;

            // 发布帖子的总积分（采纳的积分+附加功能的积分），bcadd 解决精度问题，导致的计算结果不准确  加法 
            $point = bcadd($params['point'], $StatePoint);

            // bcsub减法
            $UpdatePoint = bcsub($userInfo['point'], $point);

            if ($UpdatePoint < 0) {

                $this->error('积分不足，请先充值');
                exit;
            }

            // 开启事务
            $this->PostModel->startTrans();
            $this->UserModel->startTrans();
            $this->RecordModel->startTrans();

            $PostData = [
                'cateid' => $params['cateid'],
                'title' => $params['title'],
                'content' => $params['content'],
                'point' => $params['point'],
                'state' => $params['state'],
                'userid' => $userInfo['id']
            ];

            //插入帖子表
            $PostStatus = $this->PostModel->validate('common/Post/Post')->save($PostData);

            if ($PostStatus === FALSE) {
                $this->error($this->PostModel->getError());
                exit;
            }

            $userdata = [
                'id' => $userInfo['id'],
                'point' => $UpdatePoint
            ];

            //更新用户表
            $UserStatus = $this->UserModel->isUpdate()->save($userdata);

            if ($PostStatus === FALSE) {
                // rollback() 事务的回滚
                $this->PostModel->rollback();
                $this->error($this->UserModel->getError());
                exit;
            }

            // 插入积分记录表
            $RecordData = [
                'point' => $point,
                'state' => 1,
                'userid' => $userInfo['id']
            ];

            // 发布帖子附加功能的类型
            $state = $this->request->param('state', '');

            //判断消费状态
            switch ($state) {
                case '1':
                    $RecordData['content'] = "【" . $PostData['title'] . "】采纳积分:<b>" . $params['point'] . "积分</b> 置顶：<b>{$StatePoint}积分</b> - 发布时间：" . date("Y-m-d H:i");
                    break;
                case 2:
                    $RecordData['content'] = "【" . $PostData['title'] . "】采纳积分:<b>" . $params['point'] . "</b>积分 精华：<b>{$StatePoint}积分</b> - 发布时间：" . date("Y-m-d H:i");
                    break;
                case 3:
                    $RecordData['content'] = "【" . $PostData['title'] . "】采纳积分:<b>" . $params['point'] . "</b>积分 热门：<b>{$StatePoint}积分</b> - 发布时间：" . date("Y-m-d H:i");
                    break;
                default:
                    $RecordData['content'] = "【" . $PostData['title'] . "】采纳积分:<b>" . $params['point'] . "</b>积分 - 发布时间：" . date("Y-m-d H:i");
                    break;
            }

            //插入消费记录表
            $RecordStatus = $this->RecordModel->validate('common/User/Record')->save($RecordData);

            //插入失败
            if ($RecordStatus === FALSE) {
                $this->PostModel->rollback();
                $this->UserModel->rollback();
                $this->error($this->RecordModel->getError());
                exit;
            }

            if ($PostStatus === FALSE || $RecordStatus === FALSE || $UserStatus === FALSE) {
                $this->PostModel->rollback();
                $this->RecordModel->rollback();
                $this->UserModel->rollback();
                $this->error('发布悬赏帖子失败，请重新操作');
                exit;
            } else {
                $this->PostModel->commit();
                $this->RecordModel->commit();
                $this->UserModel->commit();
                $this->success('发布悬赏帖子成功，请等待采纳', url('home/index/index'));
                exit;
            }
        }

        // 分类列表
        $catelist = $this->CateModel->select();

        //帖子状态类别
        $statelist = $this->PostModel->state();
        // var_dump($statelist);
        // exit;

        $this->assign([
            'catelist' => $catelist,
            'statelist' => $statelist
        ]);
        return $this->fetch();
    }

    // 删帖
    public function delete()
    {
        if ($this->request->isPost()) {

            // 信息提示
            $success = [
                'result' => false,
                'msg' => ''
            ];

            // 获取所有参数postid
            $id = $this->request->param('postid');

            $postinfo = $this->PostModel->find($id);

            if (!$postinfo) {

                $success['msg'] = '没有帖子';
                $this->error('没有帖子');
                exit;
            }

            $userid = $this->LoginUser['id'];

            $userInfo = $this->UserModel->find($userid);

            if ($userid != $postinfo['userid']) {

                $success['msg'] = '没有这个权限删除该贴';
                $this->error('没有这个权限删除该贴');
                exit;
            }

            // destroy()两个参数，第一个主键ID，第二参数布尔值，默认是false（软删除）,为true是真删
            $result = $this->PostModel->destroy($id);

            if ($result == FALSE) {
                $success['msg'] = '删除失败';
                $this->error('删除失败');
                exit;
            }

            //评论直接删除 软删除
            $idList = $this->CommentModel->where(['postid' => $id])->select();

            $idarr = [];

            //循环数据拿到评论的ID
            foreach ($idList as $item) {
                array_push($idarr, $item['id']);
            }
            // 把数组转换成字符串
            $commentid = count($idarr) > 0 ? implode(',', $idarr) : '';

            // 评论做软删除
            $res = $this->CommentModel->destroy($commentid);

            if ($result === FALSE) {
                //删除失败
                $success['result'] = false;
                $success['msg'] = $this->PostModel->getError();
            } else {
                //删除成功
                $success['result'] = true;
                $success['msg'] = '删除成功';
            }

            return $success;
        }
    }

    // 删评论
    public function deletecommet()
    {

        if ($this->request->isPost()) {
            // 信息提示
            $success = [
                'result' => false,
                'msg' => ''
            ];

            // 获取所有参数postid
            $id = $this->request->param('postid');

            $pl = $this->CommentModel->find($id);
            $userid = Cookie::get('LoginUser')['id'];
            if (!$pl) {

                $success['msg'] = '没有帖子';
                $this->error('没有帖子');
                exit;
            }
            // 删除全部
            $deleteall = $this->request->param('deleteall');
            $where = [];
            $deleteall = $deleteall?$deleteall:false;
            $deleteall?$where['userid']=$userid:$where['postid']=$pl['postid'];
            //评论直接删除 软删除
            $idList = $this->CommentModel->where($where)->select();
            $idarr = [];

            //循环数据拿到评论的ID
            foreach ($idList as $item) {
                if ($item['id'] == $id || $item['pid'] == $id) {
                    array_push($idarr, $item['id']);
                }
            }
            // 把数组转换成字符串
            $commentid = count($idarr) > 0 ? implode(',', $idarr) : '';
            // 评论做软删除
            $res = $this->CommentModel->destroy($commentid);
            if ($res === FALSE) {
                //删除失败
                $success['result'] = false;
                $success['msg'] = $this->PostModel->getError();
            } else {
                //删除成功
                $success['result'] = true;
                $success['msg'] = '删除成功';
            }

            return $success;
        }
    }


    // 编辑帖子
    public function edit()
    {
        // 帖子的ID
        $id = $this->request->param('postid', 0);

        // 帖子详情
        $postinfo = $this->PostModel->with(['cate', 'user'])->find($id);

        if (!$postinfo) {
            $this->error('编辑的帖子不存在');
            exit;
        }

        //查询分类列表
        $catelist = model('Post.Cate')->order('id asc')->limit(6)->select();

        //判断登录用户id  和 发帖人的userid 是否相同
        if ($postinfo['userid'] != $this->LoginUser['id']) {

            $this->error('无权修改此帖');
            exit;
        }

        $this->assign([
            'postinfo' => $postinfo,
            'catelist' => $catelist
        ]);

        if ($this->request->isPost()) {
            // 获取所有参数
            $params = $this->request->param();

            //获取参数 如果没有就默认为空
            $vercode = $this->request->param('vercode', '');

            //判断验证码是否正确 如果结果返回true就是正确否则失败
            if (!captcha_check($vercode)) {
                $this->error('验证码输入错误');
                exit;
            }

            $data = [
                'id' => $id,
                'cateid' => $params['cateid'],
                'title' => $params['title'],
                'content' => $params['content'],
                'userid' => $this->LoginUser['id'],
                'point' => $postinfo['point'],
                'state' => $postinfo['state']
            ];

            $result = $this->PostModel->isUpdate()->save($data);

            if ($result === FALSE) {
                //修改失败
                $this->error($this->PostModel->getError());
                exit;
            } else {
                //修改成功
                $this->success('修改成功', url('home/index/info', ['postid' => $id]));
                exit;
            }
        }

        return $this->fetch();
    }
}
